from flask import request, jsonify, current_app
from flask_login import login_required, current_user
from app import db
from app.models import Conversation, Message
from app.chat import bp
from app.services.llm_service import get_llm_completion

@bp.route('/conversations', methods=['POST'])
@login_required
def create_conversation():
    data = request.get_json()
    title = data.get('title', 'New Chat') # Optional title from client

    conversation = Conversation(user_id=current_user.id, title=title)
    db.session.add(conversation)
    db.session.commit()
    return jsonify({
        'message': 'Conversation created', 
        'conversation_id': conversation.id,
        'title': conversation.title,
        'created_at': conversation.created_at.isoformat()
    }), 201

@bp.route('/conversations', methods=['GET'])
@login_required
def get_conversations():
    conversations = Conversation.query.filter_by(user_id=current_user.id).order_by(Conversation.updated_at.desc()).all()
    return jsonify([{
        'id': c.id, 
        'title': c.title, 
        'created_at': c.created_at.isoformat(),
        'updated_at': c.updated_at.isoformat()
    } for c in conversations]), 200

@bp.route('/conversations/<int:conv_id>', methods=['DELETE'])
@login_required
def delete_conversation(conv_id):
    conversation = Conversation.query.get_or_404(conv_id)
    if conversation.user_id != current_user.id:
        return jsonify({'message': 'Unauthorized'}), 403
    
    # Check if this is the last conversation
    user_conv_count = Conversation.query.filter_by(user_id=current_user.id).count()
    if user_conv_count <= 1:
        return jsonify({'message': 'Cannot delete the last conversation. At least one conversation is required.'}), 400

    db.session.delete(conversation)
    db.session.commit()
    return jsonify({'message': 'Conversation deleted'}), 200

@bp.route('/conversations/<int:conv_id>/messages', methods=['POST'])
@login_required
def send_message(conv_id):
    conversation = Conversation.query.get_or_404(conv_id)
    if conversation.user_id != current_user.id:
        return jsonify({'message': 'Unauthorized'}), 403

    data = request.get_json()
    user_content = data.get('content')
    if not user_content:
        return jsonify({'message': 'Message content is required'}), 400

    # Store user message
    user_message = Message(conversation_id=conv_id, role='user', content=user_content)
    db.session.add(user_message)
    
    # Prepare message history for LLM
    # Fetch system prompt from settings if it exists
    from app.models import SystemSetting # Avoid circular import
    system_prompt_setting = SystemSetting.query.filter_by(key='system_prompt').first()
    system_prompt_content = system_prompt_setting.value if system_prompt_setting else "You are a helpful assistant."

    messages_history = [{"role": "system", "content": system_prompt_content}]
    
    # Fetch previous messages from DB for context
    previous_messages = Message.query.filter_by(conversation_id=conv_id)\
                                     .order_by(Message.timestamp.asc()).all()
    for msg in previous_messages:
        messages_history.append({'role': msg.role, 'content': msg.content})
    
    messages_history.append({'role': 'user', 'content': user_content})

    # Get LLM response
    assistant_content = get_llm_completion(messages_history)
    if assistant_content is None or "Error:" in assistant_content:
        # Don't save user message if LLM fails, or handle error differently
        # For now, let's just return the error
        db.session.rollback() # Rollback user message if LLM call failed
        return jsonify({'message': 'Error getting response from LLM', 'details': assistant_content}), 500

    # Store assistant message
    assistant_message = Message(conversation_id=conv_id, role='assistant', content=assistant_content)
    db.session.add(assistant_message)
    
    # Update conversation's updated_at timestamp
    conversation.updated_at = db.func.now()
    db.session.add(conversation)

    db.session.commit()

    return jsonify({
        'user_message': user_message.to_dict(),
        'assistant_message': assistant_message.to_dict()
    }), 201

@bp.route('/conversations/<int:conv_id>/messages', methods=['GET'])
@login_required
def get_messages(conv_id):
    conversation = Conversation.query.get_or_404(conv_id)
    if conversation.user_id != current_user.id:
        return jsonify({'message': 'Unauthorized'}), 403

    messages = Message.query.filter_by(conversation_id=conv_id)\
                            .order_by(Message.timestamp.asc()).all()
    return jsonify([msg.to_dict() for msg in messages]), 200

@bp.route('/conversations/<int:conv_id>/rename', methods=['PUT'])
@login_required
def rename_conversation(conv_id):
    conversation = Conversation.query.get_or_404(conv_id)
    if conversation.user_id != current_user.id:
        return jsonify({'message': 'Unauthorized'}), 403

    data = request.get_json()
    new_title = data.get('title')
    if not new_title or len(new_title) > 150:
        return jsonify({'message': 'Valid title is required (max 150 chars)'}), 400

    conversation.title = new_title
    db.session.commit()
    return jsonify({'message': 'Conversation title updated', 'id': conv_id, 'new_title': new_title}), 200